package com.example.li_han.servlet;

import com.example.li_han.pojo.User;
import com.example.li_han.service.UserService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

//注册用户（添加）
@WebServlet(name = "AddUserServlet", value = "/AddUserServlet")
public class AddUserServlet extends HttpServlet {
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        BufferedReader br = req.getReader();
        StringBuilder sbuffer = new StringBuilder();
        String s;

        while((s = br.readLine()) != null) {
            sbuffer.append(s);
        }

        String requestBody = sbuffer.toString();
        System.out.println("收到注册用户请求: " + requestBody);

        Map<String, Object> resultMap = new HashMap<>();

        try {
            // 解析JSON数据
            Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
            Map<String, Object> rawData = gson.fromJson(requestBody, mapType);

            if (rawData == null) {
                resultMap.put("code", 500);
                resultMap.put("msg", "请求数据为空");
                sendResponse(resp, resultMap);
                return;
            }

            // 验证必要字段
            String zhangHao = (String) rawData.get("zhangHao");
            String password = (String) rawData.get("password");

            if (zhangHao == null || zhangHao.trim().isEmpty() ||
                    password == null || password.trim().isEmpty()) {
                resultMap.put("code", 500);
                resultMap.put("msg", "账号和密码不能为空");
                sendResponse(resp, resultMap);
                return;
            }

            // 检查账号是否已存在
            UserService userService = new UserService();
            if (userService.isZhangHaoExist(zhangHao)) {
                resultMap.put("code", 500);
                resultMap.put("msg", "账号已存在");
                sendResponse(resp, resultMap);
                return;
            }

            // 创建用户对象
            User user = new User();
            user.setZhangHao(zhangHao);
            user.setPassword(password);

            // 设置默认头像（如果有的话）
            String avatar = (String) rawData.get("avatar");
            if (avatar != null && !avatar.trim().isEmpty()) {
                user.setAvatar(avatar);
            } else {
                // 设置默认头像路径
                user.setAvatar("/images/default-avatar.png");
            }

            // 注册（添加）用户
            int result = userService.addUser(user);

            if (result > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "用户注册成功");
                resultMap.put("data", user);
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "用户注册失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "服务器异常: " + e.getMessage());
        }

        sendResponse(resp, resultMap);
    }

    private void sendResponse(HttpServletResponse resp, Map<String, Object> resultMap) throws IOException {
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }
}